﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace DNASequencing.core.FileParsing
{
    class FileReader
    {
        /// <summary>
        /// List of sequences.
        /// </summary>
        public List<String> sequences;
        
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="fileName">Input file path</param>
        public FileReader(String fileName)
        {
            sequences = process(fileName);
        }

        /// <summary>
        /// Reads sequences of DNA from input file to <i>sequences</i> variable.
        /// </summary>
        /// <param name="fileName">Input file path</param>
        /// <returns>List of strings that represents sequences</returns>
        protected List<String> process(String fileName)
        {
            if (File.Exists(fileName))
            {
                StreamReader file = null;
                sequences = new List<String>();
                try
                {
                    int read;
                    char aminoacid;
                    file = new StreamReader(fileName);
                    String sequence = "";
                    while ((read = file.Read()) > 0)
                    {
                        aminoacid = (char)read;
                        if ((aminoacid != '\r') && (aminoacid != '\n'))
                        {
                            sequence += aminoacid;
                        }
                        else
                        {
                            if (sequence.Length > 0)
                            {
                                if (sequence != "\n")
                                    sequences.Add(sequence);
                                sequence = "";
                            }
                        }
                    }
                    sequences.Add(sequence); // add last sequence
                }
                finally
                {
                    if (file != null)
                    {
                        file.Close();
                    }
                }
            }
            return sequences;
        }
    }
}
